#define _CRT_SECURE_NO_WARNINGS 1

#include "queue.h"

void QInit(Queue* pq)
{
	assert(pq);
	pq->head = pq->tail = NULL;
	pq->sz = 0;
}

void QDestroy(Queue* pq)
{
	assert(pq);
	while (pq->head)
	{
		QNode* cur = pq->head;
		pq->head = pq->head->next;
		free(cur);
		cur = NULL;
	}
	pq->head = NULL;
	pq->tail = NULL;
}

void QPush(Queue* pq, QDataType x)
{
	assert(pq);
	QNode* newnode = (QNode*)malloc(sizeof(QNode));
	if (newnode == NULL)
	{
		perror("malloc");
		return;
	}
	newnode->data = x;
	newnode->next = NULL;

	if (pq->head == NULL)
	{
		pq->head = pq->tail = newnode;
	}
	else
	{
		pq->tail->next = newnode;
		pq->tail = newnode;
	}

	pq->sz++;
}

void QPop(Queue* pq)
{
	assert(pq);
	assert(!QEmpty(pq));

	QNode* cur = pq->head;
	if (pq->head == pq->tail)
	{
		pq->head = pq->tail = NULL;
	}
	else
	{
		pq->head = pq->head->next;
	}
	free(cur);
	cur = NULL;

	pq->sz--;
}

QDataType QSize(Queue* pq)
{
	assert(pq);

	return pq->sz;
}

bool QEmpty(Queue* pq)
{
	assert(pq);

	return pq->head == NULL && pq->tail == NULL;
}

QDataType QFront(Queue* pq)
{
	assert(pq);
	assert(!QEmpty(pq));

	return pq->head->data;
}

QDataType QBack(Queue* pq)
{
	assert(pq);
	assert(!QEmpty(pq));

	return pq->tail->data;
}
